//
//  NBAPopoverViewController.m
//  NBA
//
//  Created by Jaedong on 2018/3/9.
//  Copyright © 2018年 Jaedong. All rights reserved.
//

#import "NBAPopoverViewController.h"
#import "NBAMatchView.h"
#import "NBANetworking.h"

static const CGFloat matchHeight = 75.0;
static const CGFloat totalWeight = 280.0;
static const CGFloat totalHeight = 200.0;


@interface NBAPopoverViewController ()

@property (weak) IBOutlet NSScrollView *scrollView;
@property (nonatomic, strong) NSView *documentView;
@property (weak) IBOutlet NSTextField *totalText;
@property (weak) IBOutlet NSTextField *loadingState;

@end

@implementation NBAPopoverViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
    self.view.frame = CGRectMake(0, 0, totalWeight, totalHeight);
//    [self.scrollView setHasVerticalScroller:YES];
    [self.scrollView setBorderType:NSNoBorder];
}

- (void)refreshUIs {
    [_loadingState setHidden:NO];
    _loadingState.stringValue = @"数据加载中……";
    for (NSView *view in _scrollView.contentView.subviews) {
        [view removeFromSuperview];
    }
    
    [[NBANetworking shareInstance] loadTodayMatchsWith:^(NSArray *matchs) {
        if (matchs == nil || matchs.count == 0) {
            return;
        } else {
            _totalText.stringValue = [NSString stringWithFormat:@"东哥，今天一共有%ld场比赛！", matchs.count];
            _documentView = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, totalWeight, matchs.count * matchHeight)];
            for (int i = 0 ; i < matchs.count ; i++) {
                NBAMatchView *matchView = [[NBAMatchView alloc] initWithFrame:NSMakeRect(0, matchHeight * i, totalWeight, matchHeight)];
                NSArray *array = [NSArray array];
                [[NSBundle mainBundle] loadNibNamed:@"NBAMatchView" owner:matchView topLevelObjects:&array];
                for (NSView *view in array) {
                    if ([view class] == [NBAMatchView class]) {
                        NBAMatchView *matchView = (NBAMatchView *)view;
                        [_documentView addSubview:matchView];
                        [matchView setViewDataWith:matchs[i]];
                        view.frame = NSMakeRect(0, matchHeight * i, totalWeight, matchHeight);
                    }
                }
            }
            [_scrollView setDocumentView:_documentView];
            [_loadingState setHidden:YES];
            
            //            if (matchs.count < 5) {
            self.view.frame = CGRectMake(0, 0, totalWeight, 20 + matchs.count*matchHeight);
            //            } else {
            //                self.view.frame = CGRectMake(0, 0, totalWeight, 20 + 5*matchHeight);
            //            }
        }
    } error:^(NSString *errorString) {
        _loadingState.stringValue = errorString;
    }];
    
}

@end
